package com.daniel.juc.forkjoin;

import java.util.concurrent.RecursiveTask;

/**
 * 如何使用ForkJoin
 * 1、ForkJoinPool 通过它来执行
 * 2、计算任务 forkJoinPool.execute(ForkJoinTask task)
 * 3、计算类要继承 ForkJoinTask
 *
 * @author Daniel
 * @version V1.0
 * @date 2020/5/25 10:38
 */
public class ForkJoinDemo extends RecursiveTask<Long> {

	private Long start;
	private Long end;

	// 临界值
	private Long temp = 10000L;

	public ForkJoinDemo(Long start, Long end) {
		this.start = start;
		this.end = end;
	}

	@Override
	protected Long compute() {
		if ((end - start) < temp) {
			Long sum = 0L;
			for (Long i = start; i <= end; i++) {
				sum += i;
			}
			return sum;
		} else {
			// ForkJoin递归
			Long middle = (start + end) / 2;
			ForkJoinDemo task1 = new ForkJoinDemo(start, middle);
			// 拆分任务，把任务压入线程队列
			task1.fork();
			ForkJoinDemo task2 = new ForkJoinDemo(middle + 1, end);
			// 拆分任务，把任务压入线程队列
			task2.fork();
			return task1.join() + task2.join();
		}
	}
}
